import axios from 'axios'
import {
  setToken
} from '@/utils/auth'
import { Message } from 'element-ui'
const user = {
  state: {
    token: '',
    avatar: '',
    name: '',
    id: '',
    email: '',
    phone: ''
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_PHONE: (state, phone) => {
      state.phone = phone
    },
    SET_EMAIL: (state, email) => {
      state.email = email
    },
    SET_ID: (state, id) => {
      state.id = id
    }
  },
  actions: {
    Login ({commit}, userInfo) {
      return new Promise((resolve, reject) => {
        axios.post('/api/user/login', userInfo).then(res => {
          if (res.data.msg === '用户名或密码不能为空') {
            Message.info(res.data.msg)
          } else if (res.data.msg === '用户名或密码不正确，请重试...') {
            Message.info(res.data.msg)
          }
          commit('SET_TOKEN', res.data.data.token)
          commit('SET_ID', res.data.data.id)
          setToken(res.data.data.token)
          localStorage.setItem('userId', res.data.data.id)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    GetInfo ({commit, state}) {
      const userId = localStorage.getItem('userId')
      return new Promise((resolve, reject) => {
        axios.get('/api/user/queryUser?id=' + userId).then(res => {
          commit('SET_NAME', res.data.data.name)
          commit('SET_EMAIL', res.data.data.email)
          commit('SET_PHONE', res.data.data.phone)
          commit('SET_AVATAR', res.data.data.avatar)
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    }
  }
}

export default user
